# @Time  : 2021/7/27 17:51
# @Author: zhanfengzhen
# @Email : zhanfengzhen@126.com
# @File  : basePage.py
# !/usr/bin/env python
# -*- coding: UTF-8 -*-
import os
from time import sleep

import yaml
from selenium import webdriver
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait


class BasePage:
    def __init__(self, dri : WebDriver = None):
        if dri is None:
            #创建driver对象
            self.dri = webdriver.Chrome()
            self.dri.maximize_window()
            self.dri.get('https://work.weixin.qq.com/')
            #读取yaml文件的cookies
            ff = os.path.join(os.path.dirname(__file__), '../cookiesDatas.yml')
            with open(ff, encoding='utf-8') as f:
                cookies = yaml.safe_load(f)
            for cookie in cookies:
                self.dri.add_cookie(cookie)
            self.dri.get('https://work.weixin.qq.com/wework_admin/frame#index')
            sleep(3)
        else:
            self.dri = dri

    def find(self, by, locator):
        ele = self.dri.find_element(by, locator)
        return ele

    def finds(self, by, locator):
        ele = self.dri.find_elements(by, locator)
        return ele

    def find_and_click(self, by, locator):
        ele = self.dri.find_element(by, locator)
        ele.click()

    def wait_click(self, locators, wait=10):
        ele : WebElement = WebDriverWait(self.dri, wait).until(
            expected_conditions.element_to_be_clickable(locators)
        )
        ele.click()

    def close_driver(self):
        self.dri.close()